//package com.repeat.gateway.handler;
//
//import com.alibaba.fastjson.serializer.SerializerFeature;
//import com.repeat.gateway.enums.GatewayEnum;
//import com.repeat.gateway.response.GatewayResponse;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.core.io.buffer.DataBuffer;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.MediaType;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ResponseStatusException;
//import org.springframework.web.server.ServerWebExchange;
//import org.springframework.web.server.WebExceptionHandler;
//import reactor.core.publisher.Mono;
//import com.alibaba.fastjson.JSON;
//import java.nio.charset.StandardCharsets;
//
//@Slf4j
//@Component
//public class GatewayErrorHandler implements WebExceptionHandler {
//
//    @Override
//    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
//        log.error("Gateway error occurred: ", ex);
//
//        // 定义默认响应
//        GatewayEnum errorEnum = GatewayEnum.NOT_FOUND;
//        String message = "请求路径不存在: " + exchange.getRequest().getPath();
//
//        // 根据异常类型动态调整响应（可选，按需扩展）
//        if (ex instanceof ResponseStatusException) {
//            HttpStatus status = ((ResponseStatusException) ex).getStatus();
//            if (status == HttpStatus.NOT_FOUND) {
//                errorEnum = GatewayEnum.NOT_FOUND;
//            } else if (status == HttpStatus.BAD_GATEWAY) {
//                errorEnum = GatewayEnum.BAD_GATEWAY;
//                message = "服务暂时不可用";
//            }
//            // 其他状态码处理...
//        }
//
//        // 构建统一响应
//        GatewayResponse response = new GatewayResponse(
//                errorEnum.getCode(),
//                message,
//                null
//        );
//
//        // 设置响应信息
//        exchange.getResponse().setStatusCode(HttpStatus.valueOf(errorEnum.getCode()));
//        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
//
//        // 序列化响应体
//        String jsonResponse = JSON.toJSONString(response, SerializerFeature.WriteMapNullValue);
//        DataBuffer buffer = exchange.getResponse()
//                .bufferFactory()
//                .wrap(jsonResponse.getBytes(StandardCharsets.UTF_8));
//
//        return exchange.getResponse().writeWith(Mono.just(buffer));
//    }
//}
